package com.gio.tools.common.utils;

import com.gio.tools.common.config.ProjectConfig;
import io.growing.sdk.java.GrowingAPI;
import io.growing.sdk.java.dto.GioCdpEventMessage;
import io.growing.sdk.java.dto.GioCdpUserMessage;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * GrowingIo工具类
 *
 * @author tm
 * @version 2020/10/13 19:57
 */
public class GrowingIoUtils {

    private static GrowingAPI projectA = new GrowingAPI.Builder().setProjectKey("999a3c8226515295").setDataSourceId("ba1d316beda49c8a").build();

    /**
     * 发送用户属性
     * @param druidDataSource
     * @param projectConfig
     * @param sql
     * @param varToFields
     * @param userIdField
     * @param isLog
     * @throws SQLException
     * @throws InterruptedException
     */
    public static void queryAndSendCdpUser(DataSource druidDataSource, ProjectConfig projectConfig, String sql, String[] varToFields, String userIdField, String isLog) throws SQLException, InterruptedException {
        HiveUtils hiveUtils = new HiveUtils(druidDataSource);
        ResultSet res = hiveUtils.runSql(sql);
        // 发送user
        int number = 0;
        System.out.println("--------------------正在发送用户属性，操作时间为：" + DateUtils.getDate("yyyy-MM-dd HH:mm:ss") + "-------------------------");
        while (res.next()) {
            Thread.sleep(projectConfig.getSendInterval());
            if("1".equals(isLog)){
                System.out.println("userId：" + res.getString(userIdField));
            }
            Map<String, Object> map = new HashMap<>(16);
            if(varToFields != null && varToFields.length > 0){
                for(String varToField : varToFields){
                    String var = varToField.split("-")[0];
                    String field = varToField.split("-")[1];
                    map.put(var, res.getString(field));
                }
            }

            GrowingIoUtils.sendCdpUser(res.getString(userIdField), map);
            number ++;
        }
        System.out.println("--------------------用户属性发送完毕" +  "，总数为：" + number + "-------------------------");
        hiveUtils.destruction();
    }

    /**
     * 发送用户事件
     * @param druidDataSource
     * @param projectConfig
     * @param sql
     * @param varToFields
     * @param userIdField
     * @param isLog
     * @throws SQLException
     * @throws InterruptedException
     */
    public static void queryAndSendCdpEvent(DataSource druidDataSource, ProjectConfig projectConfig, String sql, String[] varToFields, String eventKey, String userIdField, String eventTimeField, String isLog) throws SQLException, InterruptedException {
        HiveUtils hiveUtils = new HiveUtils(druidDataSource);
        ResultSet res = hiveUtils.runSql(sql);
        // 发送user
        int number = 0;
        long time = new Date().getTime();
        System.out.println("--------------------正在发送用户事件，操作时间为：" + DateUtils.getDate("yyyy-MM-dd HH:mm:ss") + "-------------------------");
        while (res.next()) {
            Thread.sleep(projectConfig.getSendInterval());
            if("1".equals(isLog)){
                Long dateLong = new Date().getTime();
                System.out.println("******************************本次用时：" + (dateLong - time) + "***************************");
                time = dateLong;
                System.out.println("userId：" + res.getString(userIdField));
                System.out.println("*************************" + eventKey + "****************************");
                System.out.println("*************************userIdField：" + res.getString(userIdField) + "****************************");
                System.out.println("*************************eventTimeField：" + res.getString(eventTimeField) + "****************************");
            }
            Map<String, Object> map = new HashMap<>(16);
            if(varToFields != null && varToFields.length > 0){
                for(String varToField : varToFields){
                    String var = varToField.split("-")[0];
                    String field = varToField.split("-")[1];
                    map.put(var, res.getString(field));
                }
            }
            GrowingIoUtils.sendCdpEvent(eventKey, res.getString(userIdField), Long.parseLong(res.getString(eventTimeField)), map);
            number ++;
        }
        System.out.println("--------------------用户事件发送完毕" +  "，总数为：" + number + "-------------------------");
        hiveUtils.destruction();
    }

    /**
     * 发送用户属性
     * @param loginUserId
     * @param map
     */
    public static void sendCdpUser(String loginUserId, Map<String, Object> map) {
        GrowingAPI.initConfig("");
        //事件行为消息体
        GioCdpUserMessage msg = new GioCdpUserMessage.Builder()
                .time(System.currentTimeMillis())
                // 默认为系统当前时间,选填
                .loginUserId(loginUserId)
                // 用户变量 (选填)
                .addUserVariables(map)
                // 用户变量集合 (选填)
                .build();
        projectA.send(msg);
    }

    /**
     * 发送事件信息
     * @param eventKey
     * @param loginUserId
     * @param map
     */
    public static void sendCdpEvent(String eventKey, String loginUserId, long eventTime, Map<String, Object> map) {
        GrowingAPI.initConfig("");
        GioCdpEventMessage msg = new GioCdpEventMessage.Builder()
                // 默认为系统当前时间 (选填)
                .eventTime(eventTime)
                // 事件标识 (必填)
                .eventKey(eventKey)
                // 登录用户ID (必填)
                .loginUserId(loginUserId)
                // 事件级变量集合 (必填)
                .addEventVariables(map)
                .build();
        projectA.send(msg);
    }

}
